package com.android.lovely.ui.fragment

import android.view.ViewGroup
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.graphics.toColorInt
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.filter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.android.lovely.R
import com.android.lovely.const.ChatChange
import com.android.lovely.const.Heart
import com.android.lovely.data.ChatHistoryList
import com.android.lovely.databinding.FragmentHomeListBinding
import com.android.lovely.databinding.ItemChatHeartBinding
import com.android.lovely.databinding.ItemChatHistoryBinding
import com.android.lovely.ext.format
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseLoadAdapter
import com.android.lovely.framework.BaseLoadFragment
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.widget.FlexibleContentContainer
import com.android.lovely.ui.activity.DetailActivity
import com.android.lovely.ui.activity.HomeActivity
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.ChatCollectListViewModel
import com.android.lovely.ui.viewmodel.ChatHeartListViewModel
import com.kotlin.extensions.appContext
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/3/11 18:46
 */
class ChatHeartFragment :
    BaseLoadFragment<FragmentHomeListBinding, ChatHistoryList>() {

    val mViewModel by activityViewModels<ChatHeartListViewModel> ()
    override fun getViewModel(): BaseLoadViewModel<ChatHistoryList> {
        return mViewModel
    }

    override fun initView() {
        getRecyclerView().layoutManager = LinearLayoutManager(requireContext())
        super.initView()
        viewLifecycleOwner.lifecycleScope.launch {
            FlowBus.flowOf<ChatChange>().collectLatest {
                mBinding.srlRefresh.isRefreshing = true
                adapter.refresh()
            }
        }
    }

    override fun setNoContent() {
        getStateLayout().setNoContentText(getString(R.string.no_heart))
        getStateLayout().setNoContentIcon(R.drawable.icon_no_content)
        getStateLayout().setNoContentButton(getString(R.string.go_chat), true) {
            startPage<HomeActivity>("position" to 1)
        }
    }

    override fun getStateLayout(): FlexibleContentContainer {
        return mBinding.flexState
    }

    override fun getSwipeRefreshLayout(): SwipeRefreshLayout {
        return mBinding.srlRefresh
    }

    override fun getRecyclerView(): RecyclerView {
        return mBinding.rv
    }

    override fun getBaseAdapter(): BaseLoadAdapter<ChatHistoryList, *> {
        val adapter = ChatHeartAdapter(mViewModel)
        adapter.itemClickListener = { item, position ->
            requireActivity().startPage<DetailActivity>("robot_id" to item.id)
        }
        return adapter
    }

    override suspend fun initData() {
        mViewModel.pager.combine(mViewModel.removedFlow) { data, remove ->
            data.filter { it.id !in remove }
        }.collectLatest {
            adapter.submitData(it)
//            adapter.refresh()
        }
    }

    override fun onResume() {
        super.onResume()
        adapter.refresh()
    }
}

class ChatHeartAdapter(val viewModel: ChatHeartListViewModel) :
    BaseLoadAdapter<ChatHistoryList, ChatHeartAdapter.ChatHeartHolder>(
        object :
            DiffUtil.ItemCallback<ChatHistoryList>() {
            override fun areItemsTheSame(
                oldItem: ChatHistoryList,
                newItem: ChatHistoryList
            ): Boolean {
                return false//oldItem.id == newItem.id
            }

            override fun areContentsTheSame(
                oldItem: ChatHistoryList,
                newItem: ChatHistoryList
            ): Boolean {
                return false//oldItem == newItem
            }

        }
    ) {
    override fun onBindViewHolder(p0: ChatHeartHolder, p1: Int) {
        val item = getItem(p1) ?: return
        p0.binding.apply {
            avatar.loadWithPlaceholder(
                item.avatar["url"]?.substringBefore("?"),
                R.drawable.icon_default_avatar
            )
            name.text = item.name
            heart.text = item.intimacyValue.toString()
            goal.setBackgroundResource(
                when (p1) {
                    0 -> R.drawable.icon_goal_1
                    1 -> R.drawable.icon_goal_2
                    2 -> R.drawable.icon_goal_3
                    else -> {
                        R.drawable.icon_goal_n
                    }
                }
            )
            goal.setTextColor(
                when (p1) {
                    0 -> "#FF9900".toColorInt()
                    1 -> "#0A9CEA".toColorInt()
                    2 ->"#EA6444".toColorInt()
                    else -> {
                       "#FFFFFF".toColorInt()
                    }
                }
            )
            (p1 + 1).toString().also { goal.text = it }
            itemRoot.clickable {
                itemClickListener?.invoke(item, p1)
            }
//            itemRoot.setOnLongClickListener {
//                itemRoot.context.showLovelyDialog {
//                    setDialogTitle(appContext.getString(R.string.delete_history))
//                    setDialogMessage(appContext.getString(R.string.delete_history_message))
//                    setPositiveButton {
//                        viewModel.delete(item.id)
//                    }
//                }
//                true
//            }
        }
    }

    private fun ItemChatHistoryBinding.setupAvatar(item: ChatHistoryList) {
        avatar.loadWithPlaceholder(
            item.avatar["url"]?.substringBefore("?"),
            R.drawable.icon_default_avatar
        )
    }

    private fun ItemChatHistoryBinding.setupNameAndMessage(item: ChatHistoryList) {
        name.text = item.name
        message.text = item.lastReply
    }

    private fun ItemChatHistoryBinding.setupUnreadCount(item: ChatHistoryList) {
        count.isVisible = item.unreadNum > 0
        count.text = getUnreadCountText(item.unreadNum)
    }

    private fun getUnreadCountText(unreadNum: Int): String {
        return if (unreadNum > 99) "99+\u0020" else "${unreadNum}\u0020"
    }

    private fun ItemChatHistoryBinding.setupLastReplyTime(item: ChatHistoryList) {
        if (item.lastReplyTimeInt > 0) {
            time.text = (item.lastReplyTimeInt * 1000L).format()
        } else {
            time.text = item.uTime
        }
    }


    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ChatHeartHolder {
        return ChatHeartHolder(p0)
    }

    class ChatHeartHolder(
        parent: ViewGroup,
        val binding: ItemChatHeartBinding = ItemChatHeartBinding.inflate(
            parent.layoutInflater,
            parent,
            false
        )
    ) : RecyclerView.ViewHolder(binding.root)
}